package cn.wolfcode.crm.realm;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.mapper.RoleMapper;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private EmployeeMapper employeeService;
    @Autowired
    private RoleMapper roleService;
    @Autowired
    private PermissionMapper permissionService;

    public String getName() {
        return "UserRealm";
    }

    //权限
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("666");
        //通过用户主体信息查询到相应角色与权限,存入授权信息里面
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Employee user = (Employee) principalCollection.getPrimaryPrincipal();
        //通过用户的id查询到相关的角色和权限,存储到权限信息对象中,交给shiro管理
        if (user.isAdmin()) {
            //如果是管理员将所有权限和角色信息存入
            info.addRole("ADMIN ");
            info.addStringPermission("*:*");
        }
       List<Role> roles = roleService.selectByEmployeeId(user.getId());
        HashSet<String> roleSn = new HashSet<>();
        for (Role role : roles) {
            roleSn.add(role.getSn());
        }
        info.addRoles(roleSn);
        List<String>permissions = permissionService.selectByEmployeeId(user.getId());
        info.addStringPermissions(permissions);
        return info;
    }

    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        //通过用户查询对应的用户信息
        Employee user =employeeService.selectByUsername(username);
        if (user== null) {
            return  null;
        }

        return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
    }
}
